#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : curl_parse_driver
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2024/2/14 21:35
# @Describe: 
# ==================================================
import argparse
import json
import warnings
from shlex import split
from http.cookies import SimpleCookie
from urllib.parse import urlparse
from w3lib.http import basic_auth_header


class CurlParser(argparse.ArgumentParser):
    def error(self, message):
        error_msg = \
            'There was an error parsing the curl command: {}'.format(message)
        raise ValueError(error_msg)

    @classmethod
    def curl_to_json(cls, curl_command, ignore_unknown_options=True):
        curl_parser = CurlParser()
        curl_parser.add_argument('url')
        curl_parser.add_argument('-H', '--header', dest='headers', action='append')
        curl_parser.add_argument('-X', '--request', dest='method', default='get')
        curl_parser.add_argument('-d', '--data-raw', dest='data')
        curl_parser.add_argument('-u', '--user', dest='auth')

        safe_to_ignore_arguments = [
            ['--compressed'],
            ['-s', '--silent'],
            ['-v', '--verbose'],
            ['-#', '--progress-bar']
        ]
        for argument in safe_to_ignore_arguments:
            curl_parser.add_argument(*argument, action='store_true')
        curl_args = split(curl_command)
        if curl_args[0] != 'curl':
            raise ValueError('A curl command must start with "curl"')
        parsed_args, argv = curl_parser.parse_known_args(curl_args[1:])
        if argv:
            msg = 'Unrecognized options: {}'.format(', '.join(argv))
            if ignore_unknown_options:
                warnings.warn(msg)
            else:
                raise ValueError(msg)
        url = parsed_args.url
        parsed_url = urlparse(url)
        if not parsed_url.scheme:
            url = 'http://' + url
        result = {'method': parsed_args.method.upper(), 'url': url}
        headers = {}
        for header in parsed_args.headers or ():
            name, val = header.split(':', 1)
            name = name.strip()
            val = val.strip()
            headers[name] = val
        if parsed_args.auth:
            user, password = parsed_args.auth.split(':', 1)
            headers['Authorization'] = basic_auth_header(user, password)
        if headers:
            result['headers'] = headers
        if parsed_args.data:
            body = parsed_args.data
            result['body'] = body
        result = json.dumps(result, indent=2, ensure_ascii=False)
        print(result, type(result))
        return result


if __name__ == '__main__':
    CurlParser.curl_to_json('''curl 'https://eva2.csdn.net/v3/06981375190026432f77c01bfca33e32/lts/groups/dadde766-b087-42da-8e67-d2499a520ee7/streams/a0119567-bf91-4314-ab75-f683ba6c0c0a/logs' \
  -H 'Accept: */*' \
  -H 'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6' \
  -H 'Connection: keep-alive' \
  -H 'Content-Type: application/json' \
  -H 'Lts-Sdk-Request-Id: 35d24698140c4681b0576877e0a7c28a' \
  -H 'Lts-Sdk-Version: 1.0.15' \
  -H 'Origin: https://blog.csdn.net' \
  -H 'Referer: https://blog.csdn.net/halps/article/details/127339661?ops_request_misc=&request_id=&biz_id=102&utm_term=python%E4%BF%9D%E5%AD%98dataframe%E5%88%B0excel%E5%B9%B6%E6%94%B9%E5%8F%98exce&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-1-127339661.142^v96^pc_search_result_base5&spm=1018.2226.3001.4187' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Site: same-site' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42' \
  -H 'X-Sdk-date: 20240214T135831Z' \
  -H 'sec-ch-ua: "Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "macOS"' \
  --data-raw '{"labels":{},"logs":[{"contents":[{"pid":"blog","ref":"","curl":"https://blog.csdn.net/halps/article/details/127339661?ops_request_misc=&request_id=&biz_id=102&utm_term=python%E4%BF%9D%E5%AD%98dataframe%E5%88%B0excel%E5%B9%B6%E6%94%B9%E5%8F%98exce&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-1-127339661.142^v96^pc_search_result_base5&spm=1018.2226.3001.4187","spm":"1001.2101","extra":"{\"x\":181,\"y\":344,\"ev\":\"move\"}","tos":8,"adb":0,"cCookie":"c_session_id=10_1707919090078.218691;c_pref=default;c_first_ref=default;c_first_page=https%3A//blog.csdn.net/halps/article/details/127339661%3Fops_request_misc%3D%26request_id%3D%26biz_id%3D102%26utm_term%3Dpython%25E4%25BF%259D%25E5%25AD%2598dataframe%25E5%2588%25B0excel%25E5%25B9%25B6%25E6%2594%25B9%25E5%258F%2598exce%26utm_medium%3Ddistribute.pc_search_result.none-task-blog-2%7Eall%7Esobaiduweb%7Edefault-1-127339661.142%5Ev96%5Epc_search_result_base5%26spm%3D1018.2226.3001.4187;c_dsid=11_1707919091558.501804;c_segment=14;c_utm_term=python%E4%BF%9D%E5%AD%98dataframe%E5%88%B0excel%E5%B9%B6%E6%94%B9%E5%8F%98exce;c_page_id=default;c_sid=416f3ece046838dd5718cfeb2c964de0;c_ref=https%3A//blog.csdn.net/halps/article/details/127339661%3Fops_request_misc%3D%26request_id%3D%26biz_id%3D102%26utm_term%3Dpython%25E4%25BF%259D%25E5%25AD%2598dataframe%25E5%2588%25B0excel%25E5%25B9%25B6%25E6%2594%25B9%25E5%258F%2598exce%26utm_medium%3Ddistribute.pc_search_result.none-task-blog-2%7Eall%7Esobaiduweb%7Edefault-1-127339661.142%5Ev96%5Epc_search_result_base5%26spm%3D1018.2226.3001.4187;c_utm_medium=distribute.pc_search_hot_word.none-task-hot_word-alirecmd-2-dataframe%20excel-null-null.172%5Ev8%5Etag_flag;","t":1707919112,"screen":"1680*1050","urn":"1707919091585-eb43c37b-0522-4ebe-8edf-274ea0257c1a","vType":"U010000","log_id":"210","sign":"5bc2d0deec0dbd3954d1ee6a02d2b38f","userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.42","cid":"10_2427687300-1681391092948-234734","uid":"qq_21913019","sid":"10_1707919090078.218691","dc_sid":"","did":"10_2427687300-1681391092948-234734","utm":"","un":"qq_21913019","__client_time__":1707919111893}]}]}' \
  --compressed''')
